//
//  XGL_LiveRoomAnchorViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/29.
//

import UIKit

class XGL_LiveRoomAnchorViewController: UIViewController,CustomNavgationBar {
    
    var liveCoverView: UIImageView!
    var inforView: XGL_LiveRoomUserItemView!
    var localView: CustomCameraView!
    var chatView: XGL_LiveRoomChatView!
    var liveId: String = ""
    var cover: UIImage?
    var time: NSInteger = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        self.createCustomBackgroundView()
        self.createXglView()
        self.creatClearNavigationBar(title: "")
        if self.localView.checkCameraPermission(){
            self.localView.startCamera()
        }else{
            self.navigationController?.popViewController(animated: true)
        }
        if let image = self.cover {
            self.liveCoverView.image = image
        }
        PanTimer.share.scheduledDispatchTimer(withName: "LiveTimer", timeInterval: 1, queue: .main, repeats: true) { timeInterval in
            self.time += 1
            if self.time % 5 == 0{
                self.getCommentDatasRequest()
            }
        }
        self.getuserDataDataRequest()
        self.getCommentDatasRequest()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        PanTimer.share.destoryTimer(withName: "LiveTimer")
    }
}

extension XGL_LiveRoomAnchorViewController{
    @objc private func moreItemAction(){
        let actionController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let action = UIAlertAction(title: "End", style: .default) { _ in
            let alertView = LiveAlertView()
            alertView.showAlertView(title: "Live End", message: "Confirm whether to end the live content") {
                let vc = XGL_LiveEndViewController()
                vc.time = self.time
                self.navigationController?.pushViewController(vc)
                if let index = self.navigationController?.viewControllers.firstIndex(where: {$0.isKind(of: XGL_LiveRoomAnchorViewController.self)}){
                    self.navigationController?.viewControllers.remove(at: index)
                }
            }
            self.view.addSubview(alertView)
            alertView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }

        let action2 = UIAlertAction(title: "Cancel", style: .cancel)
        actionController.addAction(action)
        actionController.addAction(action2)
        self.present(actionController, animated: true)
    }
}

extension XGL_LiveRoomAnchorViewController{
    private func getuserDataDataRequest(){
        PanRequestManager<XGL_RequestBaseResponse<CompleteInfor>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .PersonalInfor)) { result in
            switch result{
            case .success(let response):
                if let result = response.resultData {
                    XGL_userDataManager.share.userId = result.userId.description
                    XGL_userDataManager.share.userHeader = result.data2
                    XGL_userDataManager.share.userName = result.data1
                    self.inforView.userHeadView.userData = result
                    self.inforView.userNameText.text = result.data1
                }
                break
            default:
                break
            }
        }
    }
    
    private func getCommentDatasRequest(){
        PanRequestManager<XGL_RequestBaseResponse<PageModel<PublishCommentData>>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .GetPublishData(userId: nil, page: 1, size: 500, data1: "4", pid: self.liveId, data5: nil))) { result in
            switch result{
            case .success(let response):
                if let model = response.resultData{
                    self.chatView.chatDatas = model.data.reversed()
                    self.chatView.tableView.reloadData()
                }
                break
            default:
                break
            }
        }
    }
}

extension XGL_LiveRoomAnchorViewController{
    private func createXglView(){
        self.liveCoverView = UIImageView()
        self.localView = CustomCameraView()
        self.chatView = XGL_LiveRoomChatView()
        self.view.addSubviews([self.liveCoverView,self.localView,self.chatView])
        self.liveCoverView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.localView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.chatView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.bottom.equalTo(-BottomHeight)
            make.width.equalToSuperview().multipliedBy(0.6)
        }
    }
    
    func creatClearNavigationBar(title: String) {
        self.navigationController?.navigationBar.barStyle = .default
        setNeedsStatusBarAppearanceUpdate()
        let backColor = UIColor.clear
       
        let navView = UIView().then { make in
            make.backgroundColor = backColor
        }
        let rightItem = UIButton().then { make in
            make.setImage(imageWithName("icon_more_white"), for: .normal)
            make.addTarget(self, action: #selector(self.moreItemAction), for: .touchUpInside)
        }
        inforView = XGL_LiveRoomUserItemView().then { make in
            make.isSelf = true
        }

        navView.addSubview(rightItem)
        navView.addSubview(inforView)
        self.view.addSubview(navView)

        inforView.snp.makeConstraints { make in
            make.bottom.equalTo(-6.0)
            make.left.equalTo(15.0)
        }
        rightItem.snp.makeConstraints { make in
            make.centerY.equalTo(inforView)
            make.right.equalTo(-12.0)
            make.height.equalTo(40.0)
            make.width.equalTo(40.0)
        }
        navView.snp.makeConstraints { make in
            make.centerX.top.equalToSuperview()
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(PanNavibarH)
        }
    }
}
